<?php

namespace app\sapi\controller\v1;


use app\common\controller\Api;
use addons\third\model\Third;
use app\admin\model\Shop;
use app\common\model\User as UserModel;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use app\common\model\UserWithdrawalLog;
use think\Cache;


// use think\Request;
use wechat\AccessToken;
use wechat\Wechat;


/**
 * 中间人
 * Class Middleman
 * @package app\sapi\controller\v1
 */
class Middleman extends Api
{
    protected $noNeedLogin = ['wxMinProgramLogin'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        //监听登录成功的事件
        Hook::add('business_login_successed', function ($shop) use ($auth) {

        });
        //监听退出登陆的事件
        Hook::add('business_logout_successed', function ($shop) use ($auth) {

        });
    }

    public function wxMinProgramLogin()
    {
        $code = input('code', '0a11QKll2XlbJe4jV3ll2vtXCS01QKlJ');
        $pid = input('pid/d', 0);
        if (!$code) $this->error('自动登陆失败');
        $appid = Config::get('jmxcx.appid');
        $appSecret = Config::get('jmxcx.appsecret');

        $wechat = new Wechat($appid, $appSecret);
        $wechatUserInfo = $wechat->code2Session($code);
        \think\Log::write('小程序userinfo:'.json_encode($wechatUserInfo));
        if (isset($wechatUserInfo['errcode']) && $wechatUserInfo['errcode'] !== 0) {
            $this->error('获取用户信息失败', '', 400, 'json', ['statuscode' => 200]);
        }
        $sessionKey = $wechatUserInfo['session_key'];
        $openid = $wechatUserInfo['openid'];
        $unionid = $wechatUserInfo['unionid'];
        // $sessionKey = 'pEJRIRy0rBz7DjC0T+FmyA==';
        // $openid = 'op5kO5QrbSP9pWPY0aSgCOrWEwN8';
        // $unionid = 'oC_s565kq7a-XFjUITxyOZdHBcmA';
        if (empty($openid) || empty($sessionKey)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        // try {
            $user = (new UserModel())->where(['unionid' => $unionid,'user_type'=>3])->find();
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error('账号被封禁');
                }
                // third表有没有数据
                $third = (new Third())->where(['unionid'=>$unionid,'openid'=>$openid,'platform'=>'middleman'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'middleman';
                    $thirddata['openname'] = '';
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = $openid;
                $password = Random::alnum();
                $extend = [
                    'openid' => $openid,
                    'nickname' => '微信用户',
                    'pid' => $pid > 0 ? $pid : 0,
                    'unionid' => $unionid ?? '',
                    'user_type'=>3
                ];
                $mobile = '';
                if ($extend['unionid'] != '') {
                    $third = (new Third())->alias('t')->join('chbc_user u','t.user_id=u.id')->field('u.*,t.user_id')->where(['t.unionid'=>$extend['unionid']])->find();
                    if ($third && $third['user_id'] > 0) {
                        if ($third['mobile'] != '') $mobile = $third['mobile'];
                        if ($third['nickname'] != '' && $third['avatar'] != '') {
                            $extend['nickname'] = $third['nickname'];
                            $extend['avatar'] = $third['avatar'];
                        }
                    }
                }
                $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                if (!$ret) {
                    $this->error('注册失败，请联系管理员');
                }
                $user = (new UserModel())->where(['openid' => $openid,'unionid' => $unionid,'user_type'=>3])->find();
                // third表有没有数据
                $third = (new Third())->where(['unionid'=>$unionid,'openid'=>$openid,'platform'=>'middleman'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'middleman';
                    $thirddata['openname'] = $extend['nickname'];
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
            }
            $user['token'] = $this->auth->getToken();
            $middleman = Db::name('middleman')->where(['user_id'=>$user->id])->find();
            if (!$middleman) {
                $middleman_data['user_id'] = $user->id;
                $middleman_data['phone'] = '';
                $middleman_data['no'] = $this->generateNo(['biz_tag'=>'middleman_no','len'=>12,'int_prefix'=>6868]);
                Db::name('middleman')->insert($middleman_data);
            }
            Db::commit();
            $this->success('登陆成功',$user);
        // } catch (Exception $e) {
        //     Db::rollback();
        //     $this->error('登陆失败');
        // }
    }

    /**
     * 获取商家信息
     */
    public function info()
    {
        $user = Db::name('user')->where(['id' => $this->auth->id,'user_type'=>3])->find();
        if (empty($user)) $this->error('经纪人不存在');
        $user['token'] = $this->auth->getToken();
        $user['id_text'] = Db::name('middleman')->where('user_id',$user['id'])->value('no');
        if ($user['money']<0)$user['money']=0;
        //今日订单量
        $time0 = strtotime(date("Y-m-d", time()));
        $time24 = $time0 + 86400;

        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => ['=', $this->auth->id],
        //     'place_time' => ['between', [$time0, $time24]]
        // ])
        //     ->count();
        // $totalMoney = (new BusinessWalletLog())->where([
        //     'business_id' => ['=', $this->auth->id],
        //     'createtime' => ['between', [$time0, $time24]],
        //     'wallet' => ['<', 0],
        //     'wallet_type' => ['=', 2]
        // ])
        //     ->sum('wallet');
        // $businessInfo['today_order_num'] = $orderNum;
        // $businessInfo['today_total_money'] = abs($totalMoney);
        $this->success('经纪人信息', $user);
    }

    /**
     * 店铺列表
     * @DateTime 2023-03-22T10:23:56+0800
     * @return   [type]                   [description]
     */
    public function shopList()
    {
        $shop_status = input('shop_status/d',9);//9表示全部
        $page = input('page',1);
        $search = input('search','','htmlentities,htmlspecialchars');
        if (!$page) $page = 1;
        if ($this->auth->user_type!=3) {
            $this->error('您不是经纪人');
        }
        $user_id = $this->auth->id;
        // 查询是不是中间人，如果是中间人查询中间人介绍的店铺
        $middleman = Db::name('middleman')->where('user_id',$user_id)->find();
        if ($middleman) {
            $where = ['shop_status'=>['>=',0]];
            $where['middleman_id'] = ['=',$middleman['id']];
            if ($shop_status!=9) {
                $where['shop_status'] = ['=',$shop_status];
            }
            $where['delete_dt'] = ['null',''];
            if ($search) {
                $where['shop_name'] = ['like','%'.$search.'%'];
            }
        } else {
            $this->error('您不是经纪人');
        }
        $total = Shop::where($where)->count();
        $list = Shop::where($where)->with(['platform'])->page($page,10)->order('id DESC')->select();
        foreach ($list as $key => &$value) {
            $value->getRelation('platform')->visible(['qrcode_pic','platform_no']);
            $value['category_no'] = (float)Db::name('user_money_log')->alias('uml')->join('chbc_play_order po','uml.tran_no=po.play_order_no')->where('uml.create_dt>"'.date('Y-m-d').'" and uml.user_id='.$this->auth->id.' and log_type in (12,13) and po.shop_no='.$value['shop_no'])->value('sum(uml.money)');
        }
        $this->success('店铺列表', ['list'=>$list,'total'=>$total]);
    }


    /**
     * 收益金额
     * @return [type] [description]
     */
    public function moneyAmount()
    {
        $time = time();
        $time2 = $time-86400;
        $time3 = $time-86400*29;
        // 今日收益
        $jr = (float)Db::name('user_money_log')->where('log_type in (12,13) and user_id='.$this->auth->id.' and create_dt>="'.date('Y-m-d').'"')->value('sum(money)');
        // 昨日收益
        $zr = (float)Db::name('user_money_log')->where('log_type in (12,13) and user_id='.$this->auth->id.' and create_dt<"'.date('Y-m-d').'" and create_dt>="'.date('Y-m-d',$time2).'"')->value('sum(money)');
        // 30日收益
        $sy30 = (float)Db::name('user_money_log')->where('log_type in (12,13) and user_id='.$this->auth->id.' and create_dt>="'.date('Y-m-d',$time3).'"')->value('sum(money)');
        $this->success('收益金额', ['jr'=>$jr,'zr'=>$zr,'sy30'=>$sy30]);
    }

    /**
     * 订单分类
     * @return [type] [description]
     */
    public function playList()
    {
        $page = input('page/d', 1);
        $pageSize = 10;
        $user_id = $this->auth->id;
        $shop_no = input('shop_no', '');
        $shop = Db::name('shop')->field('logo_pic,shop_no,have_uid,phone,shop_name')->where(['shop_no'=>$shop_no])->find();
        if (!$shop) {
            $this->error('查询不到店铺');
        }
        // 四种类型的活动
        $list = [
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 1,'scheme_no'=>'图文反馈','shop_type_text'=>'美团'],// 美团图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 1,'scheme_no'=>'无需反馈','shop_type_text'=>'美团'],// 美团无需反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 2,'scheme_no'=>'图文反馈','shop_type_text'=>'饿了么'],// 饿了么图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 2,'scheme_no'=>'无需反馈','shop_type_text'=>'饿了么'],// 饿了么无需反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 3,'scheme_no'=>'图文反馈','shop_type_text'=>'京东'],// 京东图文反馈
            ['shop_no'=>$shop_no,'shop_name'=>$shop['shop_name'],'shop_type' => 3,'scheme_no'=>'无需反馈','shop_type_text'=>'京东'],// 京东无需反馈
        ];
        $start_time = time();
        $end_time = time();
        $data = [];
        foreach ($list as $key => $value) {
            $value['img'] = $shop['logo_pic'];
            $value['img_url'] = config('upload_domain').$value['img'];
            $value['order_over_num'] = 0;
            $value['acture_total_money'] = 0;
            $orders = Order::where(['shop_no'=>$shop['shop_no'],'scheme_no'=>$value['scheme_no'],'platform_no'=>$value['shop_type'],'is_pay'=>1])->field('service_charge_amt,actual_rebate_amt,create_dt,place_time')->select();
            if (!$orders) continue;
            foreach ($orders as $kk => $vv) {
                $value['order_over_num']+=1;
                $value['acture_total_money']+=$vv['service_charge_amt']+$vv['actual_rebate_amt'];
                if ($vv['place_time']<$start_time) $start_time=$vv['place_time'];
                if ($vv['place_time']>$end_time) $end_time=$vv['place_time'];
            }
            $value['acture_total_money']=round($value['acture_total_money'],2);
            if ($value['order_over_num']==0 && $value['acture_total_money']==0) continue;
            $value['id'] = $value['shop_type'].'|'.$value['shop_type_text'].'|'.$value['scheme_no'].'|'.$value['order_over_num'].'|'.$value['acture_total_money'].'|'.$value['start_date_text'].'|'.$value['end_date_text'];
            $value['play_no'] = $value['shop_type'].'|'.$value['shop_type_text'].'|'.$value['scheme_no'].'|'.$value['order_over_num'].'|'.$value['acture_total_money'].'|'.$value['start_date_text'].'|'.$value['end_date_text'].'|'.$shop['shop_no'];
            $value['shop_name'] = $shop['shop_name'];
            $data[] = $value;
        }
        $this->success('活动列表', ['list'=>$data,'total'=>count($data)]);
    }


    /**
     * 收益列表
     * @return [type] [description]
     */
    public function moneyList()
    {
        $platform_no = input('platform_no/d', 0);
        $scheme_no = input('scheme_no', '');
        // if (!$platform_no || !$scheme_no) $this->error('参数有误');
        $shop_no = input('shop_no','');
        $page = input('page/d',1);
        if (!$page) $page = 1;
        $pageSize = 10;
        $user_id = $this->auth->id;
        // if ($shop_no) {
            $sql = 'select po.*,uml.money from chbc_user_money_log uml left join chbc_play_order po on uml.tran_no=po.play_order_no where po.order_status in (3,-7,-8,-9) and uml.user_id='.$user_id.' and uml.log_type=12 and po.shop_no='.$shop_no.' order by uml.id DESC limit '.($page-1)*$pageSize.','.$pageSize;
            $list = Db::query($sql);
            $sql = 'select count(uml.id) as count from chbc_user_money_log uml left join chbc_play_order po on uml.tran_no=po.play_order_no where po.order_status in (3,-7,-8,-9) and uml.user_id='.$user_id.' and uml.log_type=12 and po.shop_no='.$shop_no;
            $total = Db::query($sql);
        // } else {
        //     $sql = 'select p.start_time_str,p.end_time_str,p.img,p.user_pay,p.shop_settlement,p.shop_type,p.start_date,p.end_date,p.shop_name,p.shop_no,uml.money from chbc_user_money_log uml left join chbc_play_order po on uml.tran_no=po.play_order_no left join chbc_play p on po.play_no=p.play_no where po.order_status in (3,-7,-8,-9) and uml.user_id='.$user_id.' and uml.log_type=12 order by uml.id DESC limit '.($page-1)*$pageSize.','.$pageSize;
        //     $list = Db::query($sql);
        //     $sql = 'select count(uml.id) as count from chbc_user_money_log uml left join chbc_play_order po on uml.tran_no=po.play_order_no left join chbc_play p on po.play_no=p.play_no where po.order_status in (3,-7,-8,-9) and uml.user_id='.$user_id.' and uml.log_type=12';
        //     $total = Db::query($sql);
        // }
        foreach ($list as $key => &$value) {
            $value['img'] = config('upload_domain').Db::name('shop')->where('shop_no',$value['shop_no'])->value('logo_pic');
            // $value['back_money_text2'] = '满'.intval($value['user_pay']).'返'.intval($value['shop_settlement']);
            $value['shop_type_text'] = config('platform')[$value['platform_no']];
            $value['place_time_text'] = date('Y-m-d H:i:s',$value['place_time']);
            // $value['start_date_text'] = date('Y-m-d',$value['start_date']);
            // $value['end_date_text'] = date('Y-m-d',$value['end_date']);
        }
        $this->success('收益列表',['list'=>$list,'total'=>$total[0]['count']]);
    }


    /**
     * 钱包明细
     * @return [type] [description]
     */
    public function moneyLog()
    {
        $page = input('page',1);
        if (!$page) $page = 1;
        $pageSize = 20;
        $user_id = $this->auth->id;
        $sql = 'select memo,money,tran_no,id,create_dt,log_type,user_id from (select memo,money,tran_no,id,create_dt,log_type,user_id from chbc_user_money_log where log_type in (13,12,11) and user_id='.$user_id.' union all select uml.memo,uml.money,uml.tran_no,uml.id,uml.create_dt,uml.log_type,uml.user_id from chbc_user_money_log uml left join chbc_user_withdrawal_log uwl on uml.tran_no=uwl.id where uml.log_type=3 and uml.before_freeze_money=0 and uwl.log_status=1 and uml.user_id='.$user_id.' and uml.after_freeze_money=0) a order by id DESC limit '.($page-1)*$pageSize.','.$pageSize;
        $user_money_log = Db::query($sql);
        if ($user_money_log) {
            foreach ($user_money_log as $key => &$value) {
                if (in_array($value['log_type'], [12,13])) {
                    $img = Db::name('play_order')->alias('po')->join('chbc_shop s','s.shop_no=po.shop_no')->where('po.play_order_no='.$value['tran_no'])->value('s.logo_pic');
                    $value['img'] = config('upload_domain').$img;
                } else {
                    $img = Db::name('user')->where(['id'=>$value['user_id']])->value('avatar');
                    $value['img'] = $img;
                }
            }
        }
        $sql = 'select count(*) as count from (select memo,money,tran_no,id from chbc_user_money_log where log_type in (13,12,11) and user_id='.$user_id.' union all select uml.memo,uml.money,uml.tran_no,uml.id from chbc_user_money_log uml left join chbc_user_withdrawal_log uwl on uml.tran_no=uwl.id where uml.log_type=3 and uml.before_freeze_money=0 and uml.after_freeze_money=0 and uml.user_id='.$user_id.' and uwl.log_status=1) a';
        $count = Db::query($sql);
        $total = $count[0]['count'];
        $this->success('钱包明细',['list'=>$user_money_log,'total'=>$total]);
    }

    public function withdrawal()
    {
        $log_mod = input('log_mod','yeepay'); // 支付宝支付alipay,微信支付wechat
        $card_no = input('card_no',''); // 账号
        $real_name = input('real_name',''); // 账号
        $money = input('money', 0);
        // if ($money>200) $this->error('单次提现不能超过200元');
        // if (!$log_mod) $this->error('缺少参数');
        // if (!$real_name && $log_mod=='alipay') $this->error('请填写真实姓名');
        $user = (new \app\common\model\User())->where([
            'id' => $this->auth->id
        ])->find();
        // if ($user->level==0) $this->error('请先激活会员');
        if (empty($user) || $user->status != 'normal') $this->error('账户异常');
        if ($money <= 0 || $money > $user->money || $user->money<0) $this->error('余额不足');
        if ($money>=500) $this->error('单次提现不能超过500元');
        $list = Db::name('user_withdrawal_log')->where(['log_status'=>1,'user_id '=>$this->auth->id,'wallet'=>$money])->find();
        if (time()-$list['with_time']<3) {
            $this->error('您操作太快啦，请稍后再试');
        }
        $extend['log_mod'] = $log_mod;
        $extend['card_no'] = $card_no;
        $extend['real_name'] = $real_name;
        $extend['withdrawal_no'] = $this->generateNo(['biz_tag'=>'withdrawal_no','len'=>12,'int_prefix'=>5]);
        Db::startTrans();
        // try {
            $user = (new \app\common\model\User())->lock(true)->where([
                'id' => $this->auth->id
            ])->find();
            $before = $user->money;
            $wallet = $money;
            $after = bcsub($before, $wallet,2);
            $desc = '';
            $data = [
                'log_mod' => $extend['log_mod'],
                'card_no' => $extend['card_no'],
                'real_name' => $extend['real_name'],
                'withdrawal_no' => $extend['withdrawal_no'],
                'user_id' => $user->id,
                'log_type' => 2,
                'wallet' => $wallet,
                'before_wallet' => $before,
                'after_wallet' => $after,
                'with_time' => time(),
                'with_desc' => $desc,
                'log_status' => 0,
                'is_merchant' => 3
            ];
            $log = UserWithdrawalLog::create($data);
            if (!$log) {Db::rollback();$this->error('日志操作有误');}
            $beans = -1*$wallet;
            // 超过200需要审核
            if ($money<200) {
                // 转账操作
                $ledger_no = Db::name('middleman')->where('user_id',$this->auth->id)->value('ledger_no');
                $divideDetail = [
                    ['ledgerNo'=>$ledger_no,'ledgerType'=>'MERCHANT_BIND_CARD','divideAmount'=>$money,'remark'=>'经纪人提现','feeChargeSide'=>'OUTSIDE','divideReason'=>'经纪人提现']
                ];
                $YopService = new \services\YopService();
                $response = $YopService->balanceApply($log['withdrawal_no'],json_encode($divideDetail,JSON_UNESCAPED_UNICODE));
                // 异步处理后续逻辑
            } else {
                //变动账户金额和冻结金额
                $res = (new UserModel())->money(-1*$beans, $user->id, '提现', $log['id'],1);
                if (!$res) {Db::rollback();$this->error('提现有误');}
            }
            Db::commit();
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     $this->error('提交失败');
        // }
        $this->success('提交成功');
    }


    public function lastRecode()
    {
        $user_id = $this->auth->id;
        $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['user_id'=>$user_id])->order('id DESC')->find();
        $this->success('上次提现记录',$user_withdrawal_log);
    }
}